'use strict';
const Controller = require('egg').Controller;
const Moment = require('moment');


class HomeController extends Controller {
  async login() {
    const { ctx, app } = this;
    const { code } = ctx.request.body;
    app.assetEmpty(code, 'code');
    const { openid } = await ctx.service.user.getOpenid(code);
    const info = await ctx.service.user.initUser({ openid });
    ctx.success(info);
  }

  async get_userinfo() {
    const { ctx } = this;
    const { openid } = ctx.request.body;
    const info = await ctx.service.user.get_userinfo(openid);
    ctx.success(info);
  }

  async project_info() {
    const { ctx, app } = this;
    const { mysql } = app;
    const info = {};
    const cites = await mysql.select('jiaolan_city');
    const disabled = await mysql.select('jiaolan_disabled')
    const actives = await mysql.select('jiaolan_active', {
      where: {
        open: 1
      },
      limit: 1
    });
    const scenes = await mysql.select('jiaolan_scene')

    if (actives.length === 0) throw new Error('没有活动开启');
    info.bg = `${app.config.assetsURL}/${actives[0].city_map}`
    info.disabled = disabled;
    info.scenes = scenes;
    info.cites = cites.map((item) => {
      const { city_map, start_date, end_date, ...rest } = item;
      const start = Moment(start_date);
      const end = Moment(end_date);
      const dates = []
      while (start.isSameOrBefore(end)) {
        dates.push({
          value: start.format('YYYY-MM-DD'),
          name: start.format('M月DD日')
        });
        start.add(1, 'd')
      }
      return {
        url: `${app.config.assetsURL}/${city_map}`,
        dates,
        ...rest
      };
    });
    ctx.success(info);
  }

  async writeOff() {
    const { ctx } = this;
    const { openid } = ctx.request.body;
    const info = await ctx.service.user.writeOff(openid);
    ctx.success(info);
  }

  async get_phone() {
    const { ctx } = this;
    const { code } = ctx.request.body;
    const info = await ctx.service.user.get_phone(code);
    ctx.success(info);
  }

  async reserve() {
    const { ctx } = this;
    const info = await ctx.service.user.reserve(ctx.request.body);
    ctx.success(info);
  }




}

module.exports = HomeController;
